default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
from myblog.mamahaoService.baseCode import getResonCode
from myblog.models import MamahaoTestGrouping, MamahaoTestRequest, MamahaoResponseContentReport
from myblog.mamahaoJOB.mamahaoJboContentSqlXML import get_sql
from myblog.mamahaoDabases import connectionDB
import logging
from django.core import serializers
from django.db.models import Q, F
import json, math, datetime, time, re

logger = logging.getLogger('log')
path = "mamahaoTestPlanAction.xml"
@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def gettingUseCases(request):
    try:
        sql = get_sql("Case", "Query", "pjAll", sqlname=path, fileName="mamahaoTestPlan")
        pj = connectionDB.getmoreSql(sql)
        sql1 = get_sql("Case", "Query", "grAll", sqlname=path, fileName="mamahaoTestPlan")
        gr = connectionDB.getmoreSql(sql1)
        sql2 = get_sql("Case", "Query", "rqAll", sqlname=path, fileName="mamahaoTestPlan")
        rq = connectionDB.getmoreSql(sql2)
        for i in range(len(pj)):
            groupList = []
            for j in range(len(gr)):
                if str(gr[j]["group_pj_id"]) == str(pj[i]["pj_id"]):
                    groupList.append(gr[j])
                    pj[i]["groupList"] = groupList
                rqlist = []
                for k in range(len(rq)):
                    if str(rq[k]["request_group_id"]) == str(gr[j]["group_id"]):
                        rqlist.append(rq[k])
                        gr[j]["rqlist"] = rqlist

        response = getResonCode().getSuccess()
        response["data"] = pj
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getTestPlanCases(request):
    """
    :param request: 获取计划筛选后测试用例
    :return:
    """
    data = json.loads(request.body)
    try:
        countSql = get_sql("Case", "Query", "queryPlanCaseCount", sqlname=path, fileName="mamahaoTestPlan")
        testsql = get_sql("Case", "Query", "queryPlanCase", sqlname=path, fileName="mamahaoTestPlan")
        sql = ""
        if data["pro_id"] != "":
            sqlpj = " AND pj.pj_id = %s" % (data["pro_id"])
            sql = sql + sqlpj
            if data["groupid"] != "":
                sqlgr = " AND gr.group_id = %s" % (data["groupid"])
                sql = sql + sqlgr
                if data["requestid"] != "":
                    sqlrq = " AND rq.request_id = %s" % (data["requestid"])
                    sql = sql + sqlrq
        if data["caseName"] != "":
            sqlcaseName = ' AND rc.case_name LIKE "%s"' % ("%" + str(data["caseName"]) + "%")
            sql = sql + sqlcaseName
        sql1 = sql
        sql = sql + " ORDER BY rc.creat_time DESC LIMIT %s,%s" % (
            (int(data["pageNum"]) - 1) * int(data["pageSize"]), data["pageSize"])

        countdata = connectionDB.getmoreSql(testsql + sql)  # 查询结果数据
        count = connectionDB.getmoreSql(countSql + sql1)  # 总数
        countNum = math.ceil(count[0]["count"] / data["pageSize"])  # 总页数
        response = getResonCode().getSuccess()
        response["data"] = countdata
        response["caseCount"] = count[0]["count"]  # 总数
        response["countNum"] = countNum  # 总页数
        response["pageNum"] = data["pageNum"]  # 当前页数
        response["pageSize"] = data["pageSize"]  # 一页多少数
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addTestPlan(request):
    """
    :param request: 添加,修改测试计划
    :return:
    """
    data = json.loads(request.body)
    try:
        planName = MamahaoResponseContentReport.objects.filter(plan_name=data["name"]).values()

        if list(planName) == []:
            testplan = MamahaoResponseContentReport(plan_name=data["name"], store_test_case=data["testCaseList"],
                                                    timing_open_close=data["timing_open_close"],
                                                    timing_task=data["timing_task"],
                                                    case_total=len(data["testCaseList"]),
                                                    remark=data["remark"], execution_state="1")
            if data["timing_open_close"] == True:
                if data["timing_task"] == "":
                    response = getResonCode().getFail()
                    response["msg"] = "输入定时任务时间不能为空"
                else:
                    data["timing_task"] = re.split(" ", data["timing_task"])
                    if len(data["timing_task"]) != 5:
                        logger.info('不正确定时任务格式：%s' % data["timing_task"])
                        response = getResonCode().getFail()
                        response["msg"] = "定时任务时间输入不正确，请重新输入"
                    else:
                        testplan.timing_task = data["timing_task"]
                        testplan.save()
                        response = getResonCode().getSuccess()
                        from myblog.mamahaoJOB.AsynchronousTaskExecution import mamahaoTask
                        mamahaoTask().start(plan_id=testplan.plan_id)
            else:
                testplan.save()
                response = getResonCode().getSuccess()
                #
        else:

            response = getResonCode().getFail()
            response["msg"] = "测试计划名称是唯一的，请重新变更‘计划名称’"
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def queryTestPlan(request):
    """
    :param request: 查询测试计划
    :return:
    """
    data = json.loads(request.body)
    print(data)
    try:
        if data["creat_time"] == None:
            data["creat_time"] = [1572537600000, 1956412800000]
        for i in range(0, 2):
            creat_time = time.localtime(data["creat_time"][i] / 1000)
            data["creat_time"][i] = time.strftime("%Y-%m-%d %H:%M:%S", creat_time)
        pageSize = data["pageSize"]
        pageNum = data["pageNum"]
        reportList = MamahaoResponseContentReport.objects.filter(
            Q(plan_name__icontains=data["plan_name"]) & Q(timing_open_close__icontains=data["timing_open_close"]) & Q(
                updata_time__range=(data["creat_time"]))).order_by("-creat_time")  # 创建时间改修改时间
        count = reportList.count()  # 总数
        datalist = json.loads(serializers.serialize("json", reportList))[
                   pageSize * pageNum - pageSize:pageSize * pageNum]
        for i in range(len(datalist)):
            creatTime = datalist[i]["fields"]["creat_time"]
            updata_time = datalist[i]["fields"]["updata_time"]
            datalist[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0] + " " + re.split('[TZ.]', creatTime)[
                1]
            datalist[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + \
                                                   re.split('[TZ.]', updata_time)[1]
        response = getResonCode().getSuccess()
        response["data"] = datalist
        response["pageNum"] = pageNum
        response["pageSize"] = pageSize
        response["gourpCount"] = count
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def deleteTestPlan(request):
    """
    :param request: 删除测试计划
    :return:
    """
    data = json.loads(request.body)
    print(data)
    try:
        mrcr = MamahaoResponseContentReport.objects.filter(plan_id=data["id"]).get()
        print(mrcr.timing_open_close)
        if mrcr.timing_open_close == 'True':
            from myblog.mamahaoJOB.AsynchronousTaskExecution import mamahaoTask
            mamahaoTask().delete(plan_id=data["id"])
        mrcr.delete()

        response = getResonCode().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)


from myblog.tasks import ExecuteTestPlanAsynchronously
from myblog.mamahaoJOB.AsynchronousTaskExecution import mamahaoTask
@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def executetTestPlan(request):
    """
    :param request: 执行测试计划
    :return:
    """
    data = json.loads(request.body)
    try:
        mamahaoTask().waitForPlan(id=data["id"])
        ExecuteTestPlanAsynchronously.delay(data["id"])
        response = getResonCode().getSuccess()
        return JsonResponse(response)
    except EOFError as e:
        mamahaoTask().errorTestPlan(id=data["id"])
        logger.error(e)
